import React, { useState, useEffect } from 'react'
import apiService from '../utils/api.js'

const CategoriesManagement = () => {
  // 分类管理相关状态
  const [categories, setCategories] = useState([])
  const [isAddingCategory, setIsAddingCategory] = useState(false)
  const [isEditingCategory, setIsEditingCategory] = useState(false)
  const [currentCategory, setCurrentCategory] = useState(null)
  const [categoryFormData, setCategoryFormData] = useState({
    name: '',
    description: ''
  })
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      setLoading(true)
      const response = await apiService.getCategories()
      if (response.code === 200 && response.data) {
        setCategories(response.data)
      } else {
        // 如果API调不通，使用模拟分类数据
        setCategories([
          { id: 1, name: '流行', description: '流行音乐' },
          { id: 2, name: '摇滚', description: '摇滚音乐' },
          { id: 3, name: '古典', description: '古典音乐' }
        ])
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
      setError('获取分类列表失败')
      // 使用模拟分类数据
      setCategories([
        { id: 1, name: '流行', description: '流行音乐' },
        { id: 2, name: '摇滚', description: '摇滚音乐' },
        { id: 3, name: '古典', description: '古典音乐' }
      ])
    } finally {
      setLoading(false)
    }
  }

  // 组件首次加载时获取分类列表
  useEffect(() => {
    fetchCategories()
  }, [])

  // 准备添加分类
  const prepareAddCategory = () => {
    setCategoryFormData({ name: '', description: '' })
    setIsAddingCategory(true)
    setIsEditingCategory(false)
    setCurrentCategory(null)
  }

  // 准备编辑分类
  const prepareEditCategory = (category) => {
    setCurrentCategory(category)
    setCategoryFormData({
      name: category.name,
      description: category.description || ''
    })
    setIsEditingCategory(true)
    setIsAddingCategory(false)
  }

  // 取消添加/编辑分类
  const cancelCategoryAction = () => {
    setIsAddingCategory(false)
    setIsEditingCategory(false)
    setCurrentCategory(null)
    setCategoryFormData({ name: '', description: '' })
  }

  // 处理添加分类
  const handleAddCategory = async (e) => {
    e.preventDefault()
    try {
      await apiService.addCategory(categoryFormData)
      cancelCategoryAction()
      fetchCategories()
    } catch (error) {
      console.error('添加分类失败:', error)
      setError('添加分类失败，请重试')
    }
  }

  // 处理编辑分类
  const handleEditCategory = async (e) => {
    e.preventDefault()
    try {
      if (currentCategory) {
        await apiService.updateCategory(currentCategory.id, categoryFormData)
        cancelCategoryAction()
        fetchCategories()
      }
    } catch (error) {
      console.error('更新分类失败:', error)
      setError('更新分类失败，请重试')
    }
  }

  // 处理删除分类
  const handleDeleteCategory = async (categoryId) => {
    if (window.confirm('确定要删除这个分类吗？删除后该分类下的所有歌曲可能会受到影响。')) {
      try {
        await apiService.deleteCategory(categoryId)
        fetchCategories()
      } catch (error) {
        console.error('删除分类失败:', error)
        setError('删除分类失败，请重试')
      }
    }
  }

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setCategoryFormData(prev => ({ ...prev, [name]: value }))
  }

  return (
    <>
      <div className="section-header">
        <button className="btn-add" onClick={prepareAddCategory}>
          添加分类
        </button>
      </div>

      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="songs-table-container">
          <table className="songs-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>分类名称</th>
                <th>描述</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {categories.map(category => (
                <tr key={category.id}>
                  <td>{category.id}</td>
                  <td>{category.name}</td>
                  <td>{category.description || '-'}</td>
                  <td>
                    <button 
                      className="btn-edit"
                      onClick={() => prepareEditCategory(category)}
                    >
                      编辑
                    </button>
                    <button 
                      className="btn-delete"
                      onClick={() => handleDeleteCategory(category.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 添加/编辑分类表单 */}
      {(isAddingCategory || isEditingCategory) && (
        <div className="song-form-modal">
          <div className="song-form">
            <h3>{isAddingCategory ? '添加分类' : '编辑分类'}</h3>
            <form onSubmit={isAddingCategory ? handleAddCategory : handleEditCategory}>
              <div className="form-group">
                <label htmlFor="categoryName">分类名称</label>
                <input
                  type="text"
                  id="categoryName"
                  name="name"
                  value={categoryFormData.name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="form-group">
                <label htmlFor="categoryDesc">描述</label>
                <input
                  type="text"
                  id="categoryDesc"
                  name="description"
                  value={categoryFormData.description}
                  onChange={handleInputChange}
                />
              </div>
              <div className="form-actions">
                <button type="button" onClick={cancelCategoryAction}>取消</button>
                <button type="submit">保存</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}

export default CategoriesManagement